package com.chen.tliaswebtest.controller;

import com.chen.tliaswebtest.pojo.Result;
import com.chen.tliaswebtest.utils.AliyunOSSOperatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/7/25
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileUploadController {
    // 允许上传的文件类型
    private static final String[] RIGTH_TYPE = {"PNG", "JPEG", "JPG"};
    // 2MB
    private static final long MAX_FILE_SIZE = 1024 * 1024 * 2;
    private final AliyunOSSOperatorUtils aliyunOSSOperator;

    public FileUploadController(AliyunOSSOperatorUtils aliyunOSSOperator) {
        this.aliyunOSSOperator = aliyunOSSOperator;
    }

    @PostMapping
    public Result upload(MultipartFile file) throws Exception {
        log.info("上传文件：{}", file);
        if (!file.isEmpty()) {
            // 图片大小限制
            if (file.getSize() > MAX_FILE_SIZE) {
                return Result.error("图片过大，上传失败");
            }
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 获取文件后缀并判断文件格式是否正确
            if (extName.isEmpty() || Arrays.stream(RIGTH_TYPE).noneMatch(type -> type.equalsIgnoreCase(extName))) {
                return Result.error("格式错误，上传失败");
            }
            // 上传文件
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            return Result.success(url);
        }
        return Result.error("上传失败");
    }
}